import { useState, useEffect, useRef } from 'react'
import axios from 'axios'


// const fetchData = async () => {
//   const response = await fetch('/api/zytq?name=厦门&n=1&apiKey=eb92c63e8b560cdc6972a96fe4d6bb32')
//   const newData = await response.text()
//   setData(newData)
//   console.log('data:', data)
// }

export default function First() {
  const [name, setName] = useState('孙悟空')
  const inputValue = useRef()
  const [character, setCharacter] = useState({})

  function enterSearchCharacter(event) {
    if (event.key === 'Enter') {
      setName(inputValue.current.value)
      inputValue.current.value = ''
    }

  }

  function searchCharacter() {
    setName(inputValue.current.value)
    inputValue.current.value = ''
  }

  useEffect(() => {

    // fetchData()
    axios({
      url: '/api/wzrw',
      method: 'GET',
      params: {
        name: name,
        apiKey: '788f6cc9add22ca434fcdfd468c5862b'
      }
    }).then((res) => {
      const data = res.data.data
      setCharacter(data)

    })
  }, [name])

  return (
    <div className='h-full flex-col '>
      <header className="flex flex-no-wrap bg-white shadow-md p-3">
        <h1 className='truncate'>THIS IS INFORMATION OF {name}</h1>
        <div className='flex flex-no-wrap'><input onKeyDown={enterSearchCharacter} ref={inputValue} placeholder='王者人物名称' className=' p-1 ml-2 mr-2 border-2 rounded-lg outline-0 border-sky-500' type='search'></input>
          <button onClick={searchCharacter} className='text-sky-500 truncate'>搜索</button></div>
      </header>

      <ul className=' flex flex-col'>
        {Object.keys(character).map((key) => (
          <li key={key} className='flex p-3'>
            <div className='flex-none font-bold'>{key}:</div>
            {key == '详情' ? (<div className='px-3'><img src={character[key]}></img></div>) : <div className='px-3'>{character[key]}</div>}
          </li>
        ))}
      </ul>
    </div>
  )
}